<template>
  <div>
    <div class="menuDescriptionBox">
      <i class="fa fa-question-circle-o fa-lg"></i>
      <span class="menuDescTitle">应用配套模板说明：</span>
      <div class="menuDesc">
        您可以在配套模板中选择该应用合适的模板，进行前端业务的创建，也可以将前端业务完全由自己开发，只使用云服务提供的业务接口，如选择云服务提供的模板，您可以进行下载并独立部署前端，也可以直接运行在云服务平台提供空间之中
        <font
          color="red"
        >（注意：如果选择直接使用云服务提供的前端层进行使用，域名无法自定义）</font>，只有PC端和H5端可以挂载在云服务中直接使用，其他类型的模板，您可以加入完成后，进行下载部署在您的WEB服务中即可，模板内部的接口请求指向地址等配置会自行完成
      </div>
    </div>
    <div class="applicationMatingTemplateMenu">
      <div
        class="applicationMatingTemplateMenuItem"
        @click="applicationMatingTemplateMenuClick(0)"
        :class="{selected : nowSelectedMenu == '0'}"
      >已加载模板</div>
      <div
        class="applicationMatingTemplateMenuItem"
        @click="applicationMatingTemplateMenuClick(1)"
        :class="{selected : nowSelectedMenu == '1'}"
      >加入新模板</div>
    </div>
    <div class="applicationMatingTemplateAdd" v-if="nowSelectedMenu == '1'">
      <el-form :model="form" :rules="rules" label-position="right" ref="form" label-width="160px">
        <el-form-item label="模板编号：" prop="templte_id">
          <el-col :span="12">
            <el-input v-model="form.templte_id" placeholder="请输入模板的编号">
              <template slot="append">
                <span style="cursor:pointer" @click="getTemplate">获取模板</span>
              </template>
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-col :span="24">
            <span style="color:#999;">提示：您可以在服务产品->官网产品->模板超市中去选择需要的模板，获取到模板的ID</span>
          </el-col>
          <el-col :span="24">
            <div class="templatePreviewBox">
              <div class="templatePreviewHint">
                <span v-if="JSON.stringify(nowTemplateData) == '{}'">模板预览区</span>
                <div class="templatePreviewImage" v-if="JSON.stringify(nowTemplateData) != '{}'">
                  <img :src="nowTemplateData.cts_template_image">
                  <div class="templatePreviewType">
                    模板类型：
                    <span v-if="nowTemplateData.cts_type == 0">Pc端</span>
                    <span v-if="nowTemplateData.cts_type == 1">H5端</span>
                    <span v-if="nowTemplateData.cts_type == 2">微信公众号端</span>
                    <span v-if="nowTemplateData.cts_type == 3">小程序端</span>
                    <span v-if="nowTemplateData.cts_type == 4">Ios端</span>
                    <span v-if="nowTemplateData.cts_type == 5">Android端</span>
                    <span v-if="nowTemplateData.cts_type == 6">Fluuter端</span>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item label="是否进行云部署：" prop="cmat_is_cloud_service">
          <el-col :span="15">
            <el-radio v-model="form.cmat_is_cloud_service" label="0">否</el-radio>
            <el-radio
              v-model="form.cmat_is_cloud_service"
              label="1"
              :disabled="nowTemplateData.cts_type > 1"
            >是</el-radio>
          </el-col>
          <el-col :span="24">
            <span style="color:#999;">提示：只有PC模板，H5模板可以支持直接进行云部署</span>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="applicationMatingTemplateBox" v-if="nowSelectedMenu == '0'">
      <div class="applicationUsedTemplateItem" v-for="item in usedTemplateData">
        <div class="applicationUsedTemplateItem_status" v-if="item.cmat_is_cloud_service == '1'">
          <template v-if="item.templateContainerInfo.status == '1'">
            <i class="fa fa-circle fa-lg" style="color:green"></i>
            <br>
            <br>运行中
          </template>
          <template v-if="item.templateContainerInfo.status == '0'">
            <i class="fa fa-circle fa-lg" style="color:red"></i>
            <br>
            <br>已停止
          </template>
        </div>
        <div class="applicationUsedTemplateItem_status" v-if="item.cmat_is_cloud_service == '0'">
          <i class="fa fa-circle fa-lg" style="color:gray"></i>
          <br>
          <br>无状态
        </div>
        <div class="applicationUsedTemplateItem_image">
          <!-- <img src="~BUSSINESS_IMAGE/images/template_1.png"> -->
          <img :src="item.templateInfo.cts_template_image">
        </div>
        <div class="applicationUsedTemplateItem_info">
          <div class="applicationUsedTemplateItem_info_item">
            <b>模板&nbsp;&nbsp;&nbsp;ID：</b>
            {{item.templateInfo.cts_template_id}}
          </div>
          <div class="applicationUsedTemplateItem_info_item">
            <b>模板类型：</b>
            <span v-if="item.templateInfo.cts_type == '0'">PC模板</span>
            <span v-if="item.templateInfo.cts_type == '1'">H5模板</span>
            <span v-if="item.templateInfo.cts_type == '2'">公众号模板</span>
            <span v-if="item.templateInfo.cts_type == '3'">小程序模板</span>
            <span v-if="item.templateInfo.cts_type == '4'">IOS模板</span>
            <span v-if="item.templateInfo.cts_type == '5'">Andorid模板</span>
            <span v-if="item.templateInfo.cts_type == '6'">Fluuter模板</span>
          </div>
          <div class="applicationUsedTemplateItem_info_item">
            <b>模板描述：</b>
            {{item.templateInfo.cts_describe}}
          </div>
          <div class="applicationUsedTemplateItem_info_item">
            <b>所属类型：</b>
            {{item.templateInfo.appProduct}}
          </div>
          <div class="applicationUsedTemplateItem_info_item">
            <template v-if="item.cmat_is_cloud_service == '1'">
              <b>公网地址：</b>
              <span>{{$global.cloudServer}}:{{item.templateContainerInfo.cmac_out_port}}/index.html</span>
            </template>
            <template v-if="item.cmat_is_cloud_service == '0'">
              <b>公网地址：</b>
              <span style="color:red;">该模板未进行非云部署，只可下载使用，不提供公网地址</span>
            </template>
          </div>
        </div>
        <div class="applicationUsedTemplateItem_action">
          <div
            class="applicationUsedTemplateItem_action_item"
            style="padding-bottom:10px;"
            v-if="item.cmat_is_cloud_service == '1'"
          >
            <el-button
              type="success"
              @click="startTemplateContainer(item.templateContainerInfo.cmac_name)"
            >启动模板</el-button>
            <el-button
              type="warning"
              @click="stopTemplateContainer(item.templateContainerInfo.cmac_name)"
            >停用模板</el-button>
            <el-button
              type="danger"
              @click="uninstallTemplateContainer(item.cmat_id,item.templateContainerInfo.cmac_id,item.templateContainerInfo.cmac_name)"
            >卸载模板</el-button>
          </div>
          <div
            class="applicationUsedTemplateItem_action_item"
            style="padding-bottom:10px;"
            v-if="item.cmat_is_cloud_service == '0'"
          >云部署的方式支持的类型只有PC模板与H5模板，其他类型的模板请进行下载部署</div>
          <div class="applicationUsedTemplateItem_action_item">
            <el-button @click="downloadTemplate(item.templateInfo.cts_template_id)">下载模板</el-button>
            <el-button
              @click="deleteTemplate(item.cmat_id,item.cmat_is_cloud_service)"
              type="danger"
            >删除模板</el-button>
          </div>
          <div class="applicationUsedTemplateItem_action_item">
            <el-button
              v-if="item.cmat_is_cloud_service == '1'"
              @click="showViewServer(item.templateContainerInfo.cmac_out_port)"
            >访问前端</el-button>
            <el-button
              v-if="item.cmat_is_cloud_service == '0'"
              type="info"
              disabled=""
            >访问前端</el-button>
            <el-button
              v-if="item.templateInfo.cts_is_template_demo == '1'"
              @click="showTemplatePreview(item.templateInfo.cts_template_id,item.templateInfo.cts_type,item.templateInfo.cts_images)"
            >模板演示</el-button>
            <el-button
              v-if="item.templateInfo.cts_is_template_demo == '0'"
              type="info"
              disabled=""
            >模板演示</el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="imagePreviewBox" v-if="isImagePreview">
            <div class="imagePreviewMain">
                <viewer :images="imagePreviewData">
                    <img v-for="item in imagePreviewData" :src="item" height="200">
                </viewer>
                <div class="closeImagePreviewBox" @click="closeImagePreviewBoxClick">
                    <i class="fa fa-close"></i>
                </div>
            </div>
        </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  //数据源
  data() {
    return {
      imagePreviewData : [],
      isImagePreview   : false,
      nowSelectedMenu: 0, //当前选中的菜单 0-已加载模板 1-加入新模板
      rules: {
        templte_id: [
          { required: true, message: "请输入模板的ID", trigger: "blur" }
        ]
      }
    };
  },
  //初始化函数
  mounted() {
    this.initData("init");
  },
  //计算属性
  computed: {
    ...mapState({
      form: state => state.ApplicationMatingTemplateModule.form,
      nowTemplateData: state =>
        state.ApplicationMatingTemplateModule.nowTemplateData,
      usedTemplateData: state =>
        state.ApplicationMatingTemplateModule.usedTemplateData
    })
  },
  //组件方法
  methods: {
    showViewServer(port){
      window.open(this.$global.cloudServer + ":" + port + "/index.html")
    },
    showTemplatePreview(template_id, cts_type, cts_images) {
      if (cts_type == "0") {
        var templateDemoUrl = this.$global.cloudServer + "/template/pc/" + template_id;
        window.open(templateDemoUrl);
      } else if (cts_type == "1") {
        var templateDemoUrl = this.$global.cloudServer + "/template/h5/" + template_id;
        window.open(templateDemoUrl, "", "width=375,height=667");
      } else {
        //获取图片数组展示数据
        this.imagePreviewData = cts_images.split("|");
        this.isImagePreview = true;

        $('.main_content').scrollTop(0);
        $('.main_content').css('overflow','hidden');
      }
    },
    closeImagePreviewBoxClick(){
        this.isImagePreview = false;
        $('.main_content').css('overflow','auto');
    },
    downloadTemplate(template_id) {

      var params = {
        username   : this.$localData.getUserName(),
        appKey     : this.$route.query.appKey,
        templateId : template_id
      }

      this.$myPop.confirmBox(
        "下载提示",
        "客户端的接口请求地址已关联到您该应用的接口服务，您无需进行任何修改，直接将客户端部署到您所需要地方即可，点击确定，进行下载",
        () => {
          this.$myLoading.startLoading();
          this.$http.postHttp(
            this.$API.userDownloadApplicationTemplate,
            params,
            rs => {
              this.$myLoading.endLoading();
              var downloadAddress = this.$global.cloudServer + rs.downloadURL
              window.open(downloadAddress)
            }
          );
        }
      );
      
    },
    deleteTemplate(cmat_id, cmat_is_cloud_service) {
      //判断是否为云部署的方式
      if (cmat_is_cloud_service == "1") {
        this.$myPop.alertBox(
          "警告提示",
          "抱歉，您需要先对该模板进行卸载操作，在进行删除"
        );
        return;
      }

      var params = {
        delete_where: "cmat_id",
        cmat_id: cmat_id,
        cmat_is_delete: 1
      };

      this.$myPop.confirmBox("确认操作", "确定要删除该模板吗？", () => {
        this.$myLoading.startLoading();
        this.$http.postHttp(
          this.$API.easydCloudMemberApplicationTemplateDelete,
          params,
          rs => {
            this.$myLoading.endLoading();
            this.$myPop.SuccessMessage();
            this.initData("update");
          }
        );
      });
    },
    startTemplateContainer(containerName) {
      var params = {
        name: containerName
      };

      this.$myLoading.startLoading();
      this.$http.postHttp(
        this.$API.dockerStartApplicationContainer,
        params,
        rs => {
          this.$myLoading.endLoading();
          this.$myPop.SuccessMessage();
          this.initData("update");
        }
      );
    },
    stopTemplateContainer(containerName) {
      var params = {
        name: containerName
      };

      this.$myLoading.startLoading();
      this.$http.postHttp(
        this.$API.dockerStopApplicationContainer,
        params,
        rs => {
          this.$myLoading.endLoading();
          this.$myPop.SuccessMessage();
          this.initData("update");
        }
      );
    },
    uninstallTemplateContainer(cmat_id, cmat_cmacid, containerName) {
      var params = {
        cmat_id: cmat_id,
        cmat_cmacid: cmat_cmacid,
        containerName: containerName
      };

      this.$myPop.confirmBox(
        "确认操作",
        "确定要卸载该模板吗，卸载后您将无法继续通过云端的方式进行访问，只能下载进行自行部署",
        () => {
          this.$myLoading.startLoading();
          this.$http.postHttp(
            this.$API.userUninstallApplicationTemplate,
            params,
            rs => {
              this.$myLoading.endLoading();
              this.$myPop.SuccessMessage();
              this.initData("update");
            }
          );
        }
      );
    },
    initData(type) {
      //获取用户在该应用下的已有模板

      if (type == "init") {
        this.$myLoading.startLoading();
      }

      this.$http.getHttp(
        this.$API.userSearchApplicationTemplate +
          "/cmat_cmaid/" +
          this.$route.query.appid +
          "/cmat_uid/" +
          this.$localData.getUserId(),
        rs => {
          if (type == "init") {
            this.$myLoading.endLoading();
          }

          this.$store.commit(
            "ApplicationMatingTemplateModule/updateUsedTemplateData",
            rs
          );
        }
      );
    },
    applicationMatingTemplateMenuClick(menu) {
      this.nowSelectedMenu = menu;
    },
    getTemplate() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$myLoading.startLoading();
          this.$http.getHttp(
            this.$API.easydCloudTemplateSupermarketSearch +
              "/cts_template_id/" +
              this.form.templte_id,
            rs => {
              this.$myLoading.endLoading();

              if (rs.data.length <= 0) {
                this.$myPop.alertBox(
                  "错误提示",
                  "抱歉，没有获取到相模板编号对应的模板，请重新尝试"
                );
                this.$store.commit("ApplicationMatingTemplateModule/clearForm");
                return;
              }

              //判断是否为同产品
              var templateData = rs.data[0];

              if (templateData.cts_capid != this.$route.query.productId) {
                this.$myPop.alertBox(
                  "错误提示",
                  "抱歉，您选择的模板与应用的产品类型不一致"
                );
                return;
              }
              this.$store.commit(
                "ApplicationMatingTemplateModule/updateNowTemplateData",
                rs.data[0]
              );
            }
          );
        }
      });
    },
    submitForm(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          if (JSON.stringify(this.nowTemplateData) == "{}") {
            this.$myPop.alertBox(
              "错误提示",
              "抱歉，您填写的模板编号可能有误，请点击获取模板进行检测是否有该模板"
            );
            return;
          }

          var params = {
            cmat_cmaid: this.$route.query.appid,
            cmat_uid: this.$localData.getUserId(),
            cmat_ctsid: this.nowTemplateData.cts_id,
            cmat_create_time: this.$common.currentTime(),
            cmat_is_cloud_service: this.form.cmat_is_cloud_service,
            username: this.$localData.getUserName(),
            template_id: this.form.templte_id,
            template_type: this.nowTemplateData.cts_type
          };

          this.$myLoading.startLoading();
          this.$http.postHttp(
            this.$API.userAddApplicationTemplate,
            params,
            rs => {
              this.$myLoading.endLoading();
              this.initData("update");
              this.$store.commit("ApplicationMatingTemplateModule/clearForm");
              this.$myPop.alertBox(
                "成功提示",
                "已经为您的应用创建了对应模板，您可以在已开模板中进行管理"
              );
            }
          );
        }
      });
    },
    resetForm() {
      this.$store.commit("ApplicationMatingTemplateModule/clearForm");
    }
  }
};
</script>

<style lang="stylus" scoped>
@import '~PUBLIC_CSS';

.applicationMatingTemplateAdd {
  width: 100%;
  height: auto;
  margin-bottom: 15px;
  padding-top: 15px;

  .templatePreviewBox {
    width: 505px;
    border-radius: 5px;
    overflow: hidden;
    height: 300px;
    border: 1px dashed #ccc;
    border-radius: 5px;
    position: relative;

    .templatePreviewImage {
      top: 0px;
      left: 0px;
      bottom: 0px;
      right: 0px;
      position: absolute;

      .templatePreviewType {
        width: 100%;
        height: 50px;
        position: absolute;
        bottom: 0px;
        left: 0px;
        background-color: rgba(0, 0, 0, 0.7);
        color: #fff;
        line-height: 50px;
        font-size: 17px;
        letter-spacing: 2px;
      }

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .templatePreviewHint {
      text-align: center;
      color: #999;
      font-size: 30px;
      line-height: 300px;
    }
  }
}

.applicationMatingTemplateMenu {
  width: 100%;
  height: 40px;
  line-height: 40px;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;

  .applicationMatingTemplateMenuItem {
    width: 120px;
    text-align: center;
    height: 100%;
    float: left;
    cursor: pointer;
  }

  .applicationMatingTemplateMenuItem.selected {
    background: #eee;
  }
}

.applicationMatingTemplateBox {
  width: 100%;
  height: auto;

  .applicationUsedTemplateItem {
    width: 100%;
    height: 175px;
    background: #f5f5f5;
    padding: 10px;
    box-sizing: border-box;
    border-radius: 5px;
    margin-bottom: 10px;
    border: 1px solid #eee;

    .applicationUsedTemplateItem_action {
      width: auto;
      height: 100%;
      float: right;
      position: absolute;
      right: 20px;

      .applicationUsedTemplateItem_action_item {
        width: 100%;
        text-align: right;
        height: auto;
        margin-bottom: 10px;
      }
    }

    .applicationUsedTemplateItem_status {
      width: 150px;
      height: 100%;
      text-align: center;
      background: #fff;
      border-radius: 5px;
      font-size: 18px;
      float: left;
      margin-right: 10px;

      i {
        margin-top: 42px;
      }
    }

    .applicationUsedTemplateItem_info {
      width: 450px;
      height: 100%;
      float: left;
      font-size: 14px;
      margin-left: 10px;
      padding-top: 4px;

      .applicationUsedTemplateItem_info_item {
        width: 100%;
        height: auto;
        margin-bottom: 12px;
      }
    }

    .applicationUsedTemplateItem_image {
      width: 200px;
      height: 100%;
      float: left;
      background: #eee;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border: 1px solid #eee;
      }
    }
  }
}
</style>